using System;
using System.Collections;
using UnityEngine;
using TMPro;

[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(MaterializeEffect))]
public class Chest : MonoBehaviour, IUseable
{
    #region Tooltip

    [Tooltip("将其设置为用于具体化效果的颜色")]

    #endregion Tooltip

    [ColorUsage(false, true)]
    [SerializeField]
    private Color materializeColor;

    #region Tooltip

    [Tooltip("将此设置为实现箱子所需的时间")]

    #endregion Tooltip

    [SerializeField]
    private float materializeTime = 3f;

    #region Tooltip

    [Tooltip("填充 withItemSpawnPoint")]

    #endregion Tooltip

    [SerializeField]
    private Transform itemSpawnPoint;

    private int healthPercent;
    private WeaponDetailsSO weaponDetails;
    private int ammoPercent;
    private Animator animator;
    private SpriteRenderer spriteRenderer;
    private MaterializeEffect materializeEffect;
    private bool isEnabled = false;
    private ChestState chestState = ChestState.closed;
    private GameObject chestItemGameObject;
    private ChestItem chestItem;
    private TextMeshPro messageTextTMP;

    private void Awake()
    {
        //  缓存组件
        animator = GetComponent<Animator>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        materializeEffect = GetComponent<MaterializeEffect>();
        messageTextTMP = GetComponentInChildren<TextMeshPro>();
    }

    /// <summary>
    /// 初始化 Chest 并使其立即可见或具体化
    /// </summary>
    public void Initialize(bool shouldMaterialize, int healthPercent, WeaponDetailsSO weaponDetails, int ammoPercent)
    {
        this.healthPercent = healthPercent;
        this.weaponDetails = weaponDetails;
        this.ammoPercent = ammoPercent;

        if (shouldMaterialize)
        {
            StartCoroutine(MaterializeChest());
        }
        else
        {
            EnableChest();
        }
    }

    /// <summary>
    /// 实现宝箱
    /// </summary>
    private IEnumerator MaterializeChest()
    {
        SpriteRenderer[] spriteRendererArray = new SpriteRenderer[] { spriteRenderer };

        yield return StartCoroutine(materializeEffect.MaterializeRoutine(GameResources.Instance.materializeShader,
            materializeColor, materializeTime, spriteRendererArray, GameResources.Instance.litMaterial));

        EnableChest();
    }

    /// <summary>
    /// 启用宝箱
    /// </summary>
    private void EnableChest()
    {
        // 将“使用”设置为“已启用”
        isEnabled = true;
    }

    /// <summary>
    /// 使用宝箱 - 动作会根据胸部状态而有所不同
    /// </summary>
    public void UseItem()
    {
        if (!isEnabled) return;

        switch (chestState)
        {
            case ChestState.closed:
                OpenChest();
                break;

            case ChestState.healthItem:
                CollectHealthItem();
                break;

            case ChestState.ammoItem:
                CollectAmmoItem();
                break;

            case ChestState.weaponItem:
                CollectWeaponItem();
                break;

            case ChestState.empty:
                return;

            default:
                return;
        }
    }

    /// <summary>
    /// 首次使用时打开宝箱
    /// </summary>
    private void OpenChest()
    {
        animator.SetBool(Settings.use, true);

        // 宝箱打开开音效
        SoundEffectManager.Instance.PlaySoundEffect(GameResources.Instance.chestOpen);

        // 检查玩家 alreay 是否有武器 - 如果有，请将 weapon 设置为空
        if (weaponDetails != null)
        {
            if (GameManager.Instance.GetPlayer().IsWeaponHeldByPlayer(weaponDetails))
                weaponDetails = null;
        }

        UpdateChestState();
    }

    /// <summary>
    /// 根据应该生成的内容和宝箱状态创建物品
    /// </summary>
    private void UpdateChestState()
    {
        if (healthPercent != 0)
        {
            chestState = ChestState.healthItem;
            InstantiateHealthItem();
        }
        else if (ammoPercent != 0)
        {
            chestState = ChestState.ammoItem;
            InstantiateAmmoItem();
        }
        else if (weaponDetails != null)
        {
            chestState = ChestState.weaponItem;
            InstantiateWeaponItem();
        }
        else
        {
            chestState = ChestState.empty;
        }
    }

    /// <summary>
    /// 实例化宝箱物品
    /// </summary>
    private void InstantiateItem()
    {
        chestItemGameObject = Instantiate(GameResources.Instance.chestItemPrefab, this.transform);

        chestItem = chestItemGameObject.GetComponent<ChestItem>();
    }

    /// <summary>
    /// 实例化玩家要收集的健康物品
    /// </summary>
    private void InstantiateHealthItem()
    {
        InstantiateItem();

        chestItem.Initialize(GameResources.Instance.heartIcon, healthPercent.ToString() + "%", itemSpawnPoint.position,
            materializeColor);
    }


    /// <summary>
    /// 收集健康物品并将其添加到玩家的生命值中
    /// </summary>
    private void CollectHealthItem()
    {
        // 检查项存在且已具体化
        if (chestItem == null || !chestItem.isItemMaterialized) return;

        // 为玩家添加生命值
        GameManager.Instance.GetPlayer().health.AddHealth(healthPercent);

        // 播放拾音器音效
        SoundEffectManager.Instance.PlaySoundEffect(GameResources.Instance.healthPickup);

        healthPercent = 0;

        Destroy(chestItemGameObject);

        UpdateChestState();
    }

    /// <summary>
    /// 实例化一个弹药项目供玩家收集
    /// </summary>
    private void InstantiateAmmoItem()
    {
        InstantiateItem();

        chestItem.Initialize(GameResources.Instance.bulletIcon, ammoPercent.ToString() + "%", itemSpawnPoint.position,
            materializeColor);
    }


    /// <summary>
    /// 收集弹药物品并将其添加到玩家当前武器的弹药中
    /// </summary>
    private void CollectAmmoItem()
    {
        // 检查项存在且已具体化
        if (chestItem == null || !chestItem.isItemMaterialized) return;

        Player player = GameManager.Instance.GetPlayer();

        //更新当前武器的弹药
        player.reloadWeaponEvent.CallReloadWeaponEvent(player.activeWeapon.GetCurrentWeapon(), ammoPercent);

        // 播放拾音器音效
        SoundEffectManager.Instance.PlaySoundEffect(GameResources.Instance.ammoPickup);

        ammoPercent = 0;

        Destroy(chestItemGameObject);

        UpdateChestState();
    }

    /// <summary>
    /// 实例化供玩家收集的武器物品
    /// </summary>
    private void InstantiateWeaponItem()
    {
        InstantiateItem();

        chestItemGameObject.GetComponent<ChestItem>().Initialize(weaponDetails.weaponSprite, weaponDetails.weaponName,
            itemSpawnPoint.position, materializeColor);
    }

    /// <summary>
    /// 收集武器并将其添加到玩家武器列表中
    /// </summary>
    private void CollectWeaponItem()
    {
        // 检查项存在且已具体化
        if (chestItem == null || !chestItem.isItemMaterialized) return;

        // 如果玩家还没有武器，则添加到播放器中
        if (!GameManager.Instance.GetPlayer().IsWeaponHeldByPlayer(weaponDetails))
        {
            // 为玩家添加武器
            GameManager.Instance.GetPlayer().AddWeaponToPlayer(weaponDetails);

            // 播放拾音器音效
            SoundEffectManager.Instance.PlaySoundEffect(GameResources.Instance.weaponPickup);
        }

        else
        {
            // 显示消息，说您已经拥有武器
            StartCoroutine(DisplayMessage("武器\n已经\n装备", 5f));
        }

        weaponDetails = null;

        Destroy(chestItemGameObject);

        UpdateChestState();
    }

    /// <summary>
    /// 在宝箱上方显示信息
    /// </summary>
    private IEnumerator DisplayMessage(string messageText, float messageDisplayTime)
    {
        messageTextTMP.text = messageText;

        yield return new WaitForSeconds(messageDisplayTime);

        messageTextTMP.text = "";
    }
}